package com.hzit.search.util;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.RemoteManagerService;
import com.ruoyi.system.api.domain.Item;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@SpringBootTest
public class ESUtil {

	@Autowired
	private ElasticsearchClient client;
	@Autowired
	private RemoteManagerService managerService;

	//1. 创建索引库创建索引结构
	@Test
	public void test01() throws IOException {
		client.indices().create(idx -> idx.index("item2")
				.mappings(mappingBuilder -> mappingBuilder
						.properties("title", propertyBuilder -> propertyBuilder.text(textProperty -> textProperty.analyzer("ik_smart").searchAnalyzer("ik_smart")))
						// .properties("title",propertyBuilder->propertyBuilder.text(textProperty->textProperty))
						.properties("price", propertyBuilder -> propertyBuilder.float_(floatProperty -> floatProperty))
						.properties("category", propertyBuilder -> propertyBuilder.keyword(keywordProperty -> keywordProperty))
						.properties("brand", propertyBuilder -> propertyBuilder.keyword(brandProperty -> brandProperty))
				));
	}

	//2. 将sku商品列表放到索引库中
	@Test
	public void test02() throws IOException {
		//2.1 从远程查询出sku商品集合
		R<List<Item>> r = managerService.findAllItems();
		List<Item> data = r.getData();

		//2.2 将查询出来的商品列表放到索引库中
		//参考官网：https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/indexing-bulk.html

		BulkRequest.Builder br = new BulkRequest.Builder();
		for (Item item : data) {
			String spec = item.getSpec();
			Map map = JSON.parseObject(spec, Map.class);
			item.setSpecMap(map);       // 为specMap字段设置值
			br.operations(op -> op
					.index(idx -> idx.index("item2")
							.id(item.getId() + "")
							.document(item)
					)
			);
		}
		//2.3 执行批量操作
		BulkResponse result = client.bulk(br.build());
		System.out.println("添加到索引库成功！");
	}

}
